// pages/course-detail/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // detail:null
        isCollect: false, //标志是否收藏
        collectid:''  //记录当前被收藏的课程id
    },
    onLoad(options) {
        wx.getStorage({ //提取本地存储
            key: 'detail',
            success: (res => {
                console.log(res)
                this.setData(res.data) //res.data必须是对象才能简写

                //初始化收藏状态
                let {
                    userInfo
                } = getApp().globalData
                let courseid = res.data.objectId //课程id
                let userid = userInfo ? userInfo.id : '' //用户id
                getApp().fly.get(`/classes/LearnCollect?where={"userid":"${userid}","courseid":"${courseid}"}`).then(collect => {
                    console.log(collect);
                    let {results} = collect.data
                    if(results.length){
                        this.setData({
                            isCollect:true,
                            collectid:results[0].objectId
                        })
                    }
                })
            })
        })

    },
    handleCollect() {  //收藏课程
        console.log(1111);
        let {
            fly,
            userLogin
        } = getApp()
        let {
            userInfo
        } = getApp().globalData
        if (!userInfo) { //判断登录状态
            userLogin() //触发一键登录
            return
        }
        console.log('收藏逻辑');
        let courseid = this.data.objectId //课程id
        let userid = userInfo.id
        let {
            artname,
            poster,
            artintro
        } = this.data
        fly.post('/classes/LearnCollect', { //收藏课程
            courseid,
            userid,
            artname,
            poster,
            artintro
        }).then(res => {
            this.setData({
                isCollect: true,
                collectid:res.data.objectId
            }) //修改本地收藏状态
        })
    },
    handleCollectDel(){  //取消收藏
        let {collectid} = this.data
        getApp().fly.delete(`/classes/LearnCollect/${collectid}`).then(res => {
            this.setData({isCollect:false})
        })
    }
})